const {execSync} = require('child_process');
const fs = require('fs');
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

/**
 * 从歌曲页面 URL 中提取歌曲 ID
 */
function getSongIdFromUrl(url) {
    const match = url.match(/id=(\d+)/);
    return match ? match[1] : null;
}

/**
 * 检测 Chrome
 * @returns {string|null} 有效的 Chrome 可执行文件路径
 */
function findChrome() {
    try {
        const output = execSync('where chrome', { stdio: 'pipe' }).toString().trim();
        const lines = output.split('\n').map(l => l.trim()).filter(Boolean);
        const foundPath = lines.find(p => p.toLowerCase().endsWith('chrome.exe'));
        if (foundPath && fs.existsSync(foundPath)) {
            console.log('✅ 使用系统 Chrome:', foundPath);
            return foundPath;
        }
    } catch (e) {
        // 忽略 where 错误
        console.log(e);
    }
    console.warn('⚠️ 未找到 Chrome');
    return null;
}


module.exports = {
    sleep,
    randomInt,
    getSongIdFromUrl,
    findChrome,
};